package portal.controller;


import beans.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.beans.Node;
import portal.dao.ScheduleNodeDetailDao;
import utils.UserLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description //TODO 计算节点相关
 * @deprecated 涉及节点操作相关已在 HostAction中实现  Since 2019-01-17
 * @Author HMY
 **/
@WebServlet(name="NodeServlet")
@Deprecated
public class NodeServlet extends BaseServlet {
    private static final long serialVersionUID = -3162830938790827981L;
    @Autowired
    ScheduleNodeDetailDao scheduleNodeDetailDao ;
    private String token;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName = request.getParameter("method");
        Method method = null;
        try {
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * By黄梦阳 //TODO 新增计算节点
     *
     * @return void
     * @Param [request, response]
     **/
    protected void addNode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeName = request.getParameter("nodeName");
        String nodeIp = request.getParameter("nodeIp");
        String gpuIdStr = request.getParameter("gpuId");
        gpuIdStr = gpuIdStr==null?"0":gpuIdStr;
        String groupName = request.getParameter("groupName");

        Node node = new Node();
        node.setNodeName(nodeName == null ? "" : nodeName);
        node.setNodeIp(nodeIp);
        node.setGpuId(Integer.parseInt(gpuIdStr));
        node.setGroupName(groupName == null ? "" : groupName);
        node.setStatus("在线");

        JSONObject result = new JSONObject();
        boolean nameflag = scheduleNodeDetailDao.isExistName(nodeName);
//        System.out.println("nameflag==="+nameflag);
        if (nameflag) {
            result.put("result", "false");
            result.put("message", "新增节点与(ip)节点名相同，请检查集群配置");
        }
        boolean ipflag = scheduleNodeDetailDao.isExistIp(nodeIp);
//        System.out.println("ipflag==="+ipflag);
        if (ipflag) {
            result.put("result", "false");
            result.put("message", "新增节点与(ip)节点名相同，请检查集群配置");
        }
        if (!nameflag && !ipflag) {
            boolean addflag = scheduleNodeDetailDao.addNode(node);
            if (addflag) {
                result.put("result", "success");
                result.put("message", "新增节点注册成功");
                //日志记录
                String userId = (String) request.getSession().getAttribute("userId");
                UserLogUtil.dbLog(LogEnum.node
                        , LogEnum.add
                        , userId
                        , LogEnum.node.getValue() + "IP：" + node.getNodeIp() + "，主机名：" + node.getNodeName());
            } else {
                result.put("result", "false");
                result.put("message", "新增节点注册失败，请联系相关人员处理");
            }
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 查询所有计算节点
     *
     * @return void
     * @Param [request, response]
     **/
    protected void getAllNode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        List<Object> nodeList = scheduleNodeDetailDao.getAllNode();
        JSONObject result = new JSONObject();
        if (nodeList != null && nodeList.size() != 0) {
            result.put("result", "success");
            result.put("message", JSONArray.fromObject(nodeList));
        } else {
            result.put("result", "false");
            result.put("message", "无相关信息");
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 分页查询计算节点
     *
     * @return void
     * @Param [request, response]
     **/
    protected void getPagedNode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
//        System.out.println(onePageCount);
        List<Object> pagedNodeList = scheduleNodeDetailDao.getPagedNodeList(onePageCount, currentPage);
        int pageNum = scheduleNodeDetailDao.getNodePageNum(onePageCount);
        JSONObject result = new JSONObject();
        if (pagedNodeList != null && pagedNodeList.size() > 0) {
            result.put("result", "success");
            JSONObject message = new JSONObject();
            message.put("pageNum", pageNum);
            message.put("pagedNodeList", JSONArray.fromObject(pagedNodeList));
            result.put("message", message);
        } else {
            result.put("result", "false");
            result.put("message", "查询不到信息");
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 根据节点id改变指定节点的状态
     *
     * @return void
     * @Param [request, response]
     **/
    protected void modifyNodeStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeIdStr = request.getParameter("nodeId");
        int nodeId = Integer.parseInt(nodeIdStr == null ? "" : nodeIdStr);
        String statusOperation = request.getParameter("statusOperation");
//        System.out.println(nodeIdStr);
//        System.out.println(statusOperation);
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        Node node = scheduleNodeDetailDao.getNodeByNodeId(nodeId);
        Node newNode = new Node();
        newNode.setRemain_mem(node.getRemain_mem());
        newNode.setCpuRatio(node.getCpuRatio());
        newNode.setNodeId(node.getNodeId());
        newNode.setNodeName(node.getNodeName());
        newNode.setNodeIp(node.getNodeIp());
        newNode.setGpuId(node.getGpuId());
        newNode.setGroupName(node.getGroupName());
        newNode.setStatus("下线".equals(statusOperation) ? "下线" : "在线");
        boolean modifyflag = scheduleNodeDetailDao.updateNode(node, newNode);
//        System.out.println(modifyflag);
        JSONObject result = new JSONObject();
        if (modifyflag) {
            result.put("result", "success");
            result.put("message", statusOperation + "操作成功");
            //日志记录
            String userId = (String) request.getSession().getAttribute("userId");
            UserLogUtil.dbLog(LogEnum.node
                    , LogEnum.update
                    , userId
                    , LogEnum.node.getValue() + "IP：" + node.getNodeIp() + "，主机名：" + node.getNodeName());
        } else {
            result.put("result", "false");
            result.put("message", statusOperation + "操作失败");
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 根据节点id修改指定节点信息
     *
     * @return void
     * @Param [request, response]
     **/
    protected void modifyNode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeIdStr = request.getParameter("nodeId");
        int nodeId = Integer.parseInt(nodeIdStr == null ? "" : nodeIdStr);
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        Node node = scheduleNodeDetailDao.getNodeByNodeId(nodeId);

        String remain_mem = request.getParameter("remain_mem");
        String cpuRatio = request.getParameter("cpuRatio");
        String nodeIp = request.getParameter("nodeIp");
        String nodeName = request.getParameter("nodeName");
        String gpuIdStr = request.getParameter("gpuId");
        gpuIdStr = gpuIdStr==null?"0":gpuIdStr;
        String groupName = request.getParameter("groupName");
        //String status = request.getParameter("status");

        Node newNode = new Node();
        newNode.setRemain_mem(remain_mem);
        newNode.setCpuRatio(cpuRatio);
        newNode.setNodeIp(nodeIp);
        newNode.setNodeId(node.getNodeId());
        newNode.setNodeName(nodeName);
        newNode.setGpuId(Integer.parseInt(gpuIdStr));
        newNode.setGroupName(groupName);
        newNode.setStatus(node.getStatus());

        boolean modifyflag = scheduleNodeDetailDao.updateNode(node, newNode);
        JSONObject result = new JSONObject();
        if (modifyflag) {
            result.put("result", "success");
            result.put("message", "修改计算节点信息成功");
            //日志记录
            String userId = (String) request.getSession().getAttribute("userId");
            UserLogUtil.dbLog(LogEnum.node
                    , LogEnum.update
                    , userId
                    , LogEnum.node.getValue() + "IP：" + node.getNodeId() + "，主机名：" + node.getNodeName());
        } else {
            result.put("result", "false");
            result.put("message", "修改计算节点信息失败");
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 删除指定计算节点
     *
     * @return void
     * @Param [request, response]
     **/
    protected void deleteNode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeIdStr = request.getParameter("nodeId");
        int nodeId = Integer.parseInt(nodeIdStr == null ? "" : nodeIdStr);
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        Node node = scheduleNodeDetailDao.getNodeByNodeId(nodeId);
        boolean deleteflag = scheduleNodeDetailDao.deleteNode(nodeId);
        JSONObject result = new JSONObject();
        if (deleteflag) {
            result.put("result", "success");
            result.put("message", "删除成功");
            //日志记录
            String userId = (String) request.getSession().getAttribute("userId");
            UserLogUtil.dbLog(LogEnum.node
                    , LogEnum.delete
                    , userId
                    , LogEnum.node.getValue() + "IP：" + node.getNodeId() + "，主机名：" + node.getNodeName());
        } else {
            result.put("result", "false");
            result.put("message", "删除失败");
        }
        response.getWriter().write(result.toString());
    }

    /**
     * By黄梦阳 //TODO 根据nodeId查询指定节点的信息
     *
     * @return void
     * @Param [request, response]
     **/
    protected void getNodeById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nodeIdStr = request.getParameter("nodeId");
        int nodeId = Integer.parseInt(nodeIdStr == null ? "" : nodeIdStr);
        ScheduleNodeDetailDao scheduleNodeDetailDao = new ScheduleNodeDetailDao();
        Node node = scheduleNodeDetailDao.getNodeByNodeId(nodeId);
        JSONObject result = new JSONObject();
        if (node != null) {
            result.put("result", "success");
            result.put("message", JSONObject.fromObject(node));
        } else {
            result.put("result", "false");
            result.put("message", "查询失败");
        }
        response.getWriter().write(result.toString());
    }
}